<!--
 * @Author: zsc
 * @Date: 2022-06-13 21:56:52
 * @LastEditors: zsc
 * @LastEditTime: 2022-07-26 21:19:32
 * @Description:
-->

<template>

  <el-dialog
    :before-close="beforeClose"
    :visible.sync="show"
    :title="title"
    width="80%"
    @close="close"
    @closed="closed"
  >
    <div class="app-container">
      <el-card class="app-container-tools">
        <div class="app-container-tools-search">
          <span>房间号：</span>
          <el-input v-model="WHERE.search" class="k-width-150-p k-mr-10" />
          <el-button type="primary" @click="_search">查询</el-button>
          <el-button type="primary" @click="_reset">重置</el-button>
        </div>
        <div class="app-container-tools-action">
          <el-button v-permission="['BD:ROOM:ADD']" type="primary" style=" margin-left: 10px" @click="handleCreate">新增</el-button>
          <el-button v-permission="['BD:ROOM:IMPORT']" class="k-mr-10"> <el-upload
            action=""
            :show-file-list="false"
            :multiple="false"
            :file-list="fileList"
            :before-upload="uploadChangeHandel"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          >导入</el-upload>
          </el-button>
          <el-button v-permission="['BD:ROOM:IMPORT']" class="k-mr-10">
            <a download="房间导入模板.xlsx" href="/template/房间导入模板.xlsx">导入模板下载</a>
          </el-button>
        </div>
      </el-card>
      <el-card>
        <!--    表格-->
        <el-table
          ref="tb"
          v-loading="LOADING"
          :data="TABLE_DATA"
          :size="SIZE"
          border
          :height="LIST_HEIGHT_DIALOG"
          style="width: 100%"
          @selection-change="_handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <template v-for="(item) in setting">
            <el-table-column
              v-if="item.key === 'action'"
              :key="item.id"
              :label="item.name"
              :prop="item.key"
              :width="item.value"
              :fixed="item.fixed"
            >
              <template slot-scope="scope">
                <el-button v-permission="['BD:ROOM:EDIT']" @click="handleUpdate(scope.row)">编辑</el-button>
                <el-button v-permission="['BD:ROOM:DEL']" @click="handleDel(scope.row)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column
              v-else-if="item.key === 'region'"
              :key="item.id"
              :label="item.name"
              :prop="item.key"
              :width="item.value"
              :fixed="item.fixed"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.region_info.province+'/'+scope.row.region_info.city+'/'+scope.row.region_info.county+'/' }}</span>
              </template>

            </el-table-column>

            <el-table-column
              v-else
              :key="item.id"
              :label="item.name"
              :prop="item.key"
              :width="item.value"
            />
          </template>
        </el-table>
        <!--    分页-->
        <pagination />
        <!--    弹窗-->
        <form-modal :visible.sync="FORM_VISIBLE" :type="FORM_TYPE" :data="FORM_DATA" :building-id="buildingId" :region-id="regionId" @refresh="_search" />
        <room-scan-modal :visible.sync="scanVisible" :data="scanId" />
      </el-card>
    </div>
  </el-dialog>

</template>

<script>
import list from '@/list'
import RoomClass from '@/models/room-class'
import { roomGetList, roomDel, roomBlukCreate } from '@/api/room'
import formModal from './form'
import roomScanModal from '@/views/company/list/components/scan'
import * as XLSX from 'xlsx'
const roomClass = new RoomClass()
export default {
  name: 'RoomList',
  components: { formModal, roomScanModal },
  mixins: [list],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    buildingId: {
      type: Number,
      default: 0
    },
    buildingName: {
      type: String,
      default: ''
    },
    regionId: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      show: false,
      caseRequestURLType: '',
      setting: roomClass.list(),
      scanVisible: false,
      scanId: 0,
      WHERE: {
        search: '',
        building_id: this.buildingId
      },
      fileList: []

    }
  },
  computed: {
    title() {
      return this.buildingName + '-房间管理'
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.show = val
        this.WHERE.building_id = this.buildingId
        this._search()
      }
    }
  },
  created() {
    this.LIST_API = roomGetList
  },
  mounted() {
  },
  methods: {

    handleCreate() {
      console.log('添加')
      this.FORM_TYPE = 'create'
      this.FORM_VISIBLE = true
      this.FORM_DATA = { }
    },
    handleUpdate(item) {
      console.log('更新')
      this.FORM_TYPE = 'edit'
      this.FORM_VISIBLE = true
      this.FORM_DATA = item
    },
    handleImport() {
      console.log('导入')
      this.$notify.success('导入')
    },

    handleDel(item) {
      console.log('删除', item)
      this.$confirm('确认删除？')
        .then(_ => {
          roomDel(item.id).then(p => {
            this._showSuccess('删除成功')
            this._search()
          })
        })
        .catch(_ => {
        })
    },
    handleCompany(item) {
      console.log('查看')
      this.scanVisible = true
      this.scanId = item.id
    },
    csvToArray(str, delimiter = ',') {
      const header_cols = str.slice(0, str.indexOf('\n')).split(delimiter)
      const row_data = str.slice(str.indexOf('\n') + 1).split('\n')
      const arr = row_data.map(function(row) {
        const values = row.split(delimiter)
        const el = header_cols.reduce(function(object, header, index) {
          object[header] = values[index]
          return object
        }, {})
        return el
      })
      return arr
    },
    async uploadChangeHandel(file) {
      const reader = new FileReader(file)
      reader.readAsBinaryString(file)
      reader.onload = async(e) => {
        const data = e.target.result
        const workbook = XLSX.read(data, { type: 'binary' })
        const sheet = workbook.Sheets
        var aoa = XLSX.utils.sheet_to_csv(sheet[workbook.SheetNames[0]])
        const arrData = this.csvToArray(aoa, ',').filter(
          (p) => { return p['房间号'] && p['楼层'] }
        )
        const upData = arrData.map((p) => {
          return {
            'name': p['房间号'],
            'floor_num': p['楼层'],
            'area': p['房间面积(㎡)'],
            'note': p['备注'],
            'building_id': this.buildingId,
            'region_id': this.regionId,
            'company_id': 0

          }
        })
        roomBlukCreate({ building_id: this.buildingId, rooms: upData }).then(
          p => {
            this.$notify({
              title: 'Success',
              dangerouslyUseHTMLString: true,
              message: `
            操作成功!
          `,
              type: 'success'
            })
            this._getList()
          }
        )

        // await focusCreate({ list: upData })
      }
      this.fileList = []
      return false
    },
    handleImportTemplate() {
      console.log('导入模板下载')
    },
    handleClose() {
      console.log('点击关闭')
      this.beforeClose()
    },
    beforeClose() {
      console.log('关闭前的回调')
      this.show = false
      this.$emit('update:visible', false)
    },
    close() {
      console.log('关闭的回调')
    },
    closed() {
      console.log('关闭动画结束后的回调')
    }
  }
}
</script>
<style lang="scss">
 @import '@/styles/list/index.scss';
</style>
